<script setup>
import {ref, defineProps, watchEffect, defineEmits} from "vue";
const props = defineProps({
  label: {
    type:String,
    default:""
  },
  value: {
    type:String,
    default:""
  },
  placeholder:{
    type:String,
    default:"输入框提示内容"
  },
  type:{
    type: String,
    default: "text"
  },
  rule:{
    type: String,
    default:null
  },
  error:{
    type:String,
    default:"数据不合法"
  },
  success:{
    type:String,
    default:""
  }
});
//定义自定义事件
const emit = defineEmits(["passValue"]);

let value = ref(props.value);
//数据校验结果
let result = ref(false);

watchEffect(function (){
  if(props.rule) {
    //进行数据的校验, 将字符串rule转换成一个正则对象
    const re = new RegExp(props.rule);
    result.value = re.test(value.value);
    if (result.value == true) {
      emit("passValue", value.value);
    }
  }else{
    emit("passValue", value.value);
  }
});
</script>

<template>
  <el-row :gutter="20" style="margin: 5px 0;">
    <el-col :span="label ? 4:0" class="label-class-col">
      <label class="label-class">{{label}}</label>
    </el-col>
    <el-col :span="label ? 20:24">
      <el-input :clearable="type != 'password' ? true:false" :show-password="type == 'password' ? true:false" v-model="value" :type="type" :placeholder="placeholder"></el-input>
    </el-col>
    <el-col :span="label ? 20:24" :offset="label ? 4:0" style="padding-top: 5px;font-size: 14px;">
      <slot v-if="value && rule">
        <div :class="{error: !result, success: result}"><i :class="{iconfont:true, 'icon-cuowu': !result, 'icon-duihao2': result}" style="margin-right: 5px"></i>{{result ? success:error}}</div>
      </slot>
    </el-col>
  </el-row>
</template>

<style scoped lang="less">
.label-class {
  display: block;
  text-align: right;
  font-size: 14px;
}
.label-class-col {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.error{
  color: red;
  text-align: left;
}
.success {
  color: #228522;
  text-align: left;
}
</style>